package com.carleasoft.mps.cms.business.education.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.cms.business.article.constants.ExceptionCMSEnum;
import com.carleasoft.mps.cms.business.article.service.ArticleService;
import com.carleasoft.mps.cms.business.clerk.bean.DealProcessEntity;
import com.carleasoft.mps.cms.business.clerk.service.DealProcessService;
import com.carleasoft.mps.cms.business.collector.bean.entity.CollectorEntity;
import com.carleasoft.mps.cms.business.collector.service.CollectorService;
import com.carleasoft.mps.cms.business.drug.bean.entity.DrugOilManage;
import com.carleasoft.mps.cms.business.education.bean.entity.EducationEntity;
import com.carleasoft.mps.cms.business.education.bean.entity.EducationCollectEntity;
import com.carleasoft.mps.cms.business.education.bean.entity.EducationBasicEntity;
import com.carleasoft.mps.cms.business.education.bean.entity.EducationOpenEntity;
import com.carleasoft.mps.cms.business.education.bean.po.EducationDoorPagePo;
import com.carleasoft.mps.cms.business.education.bean.po.EducationPageQueryPo;
import com.carleasoft.mps.cms.business.education.bean.po.EducationPo;
import com.carleasoft.mps.cms.business.education.bean.po.EducationCodePo;
import com.carleasoft.mps.cms.business.education.bean.vo.*;
import com.carleasoft.mps.cms.business.education.bean.vo2.EduBasicVo;
import com.carleasoft.mps.cms.business.education.bean.vo2.EduCollectVo;
import com.carleasoft.mps.cms.business.education.bean.vo2.EduOpenVo;
import com.carleasoft.mps.cms.business.education.bean.vo2.EduVo;
import com.carleasoft.mps.cms.business.education.dao.EduDoorMapper;
import com.carleasoft.mps.cms.business.education.service.EducationService;
import com.carleasoft.mps.cms.business.education.service.EduCollectService;
import com.carleasoft.mps.cms.business.education.service.EduOpenService;
import com.carleasoft.mps.cms.business.education.service.EduDoorService;
import com.carleasoft.mps.cms.business.user.bean.UserSkill;
import com.carleasoft.mps.cms.business.user.service.UserSkillService;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.user.UserDeptVo;
import com.carleasoft.mps.core.user.UserPro;
import com.carleasoft.mps.core.utils.IBeanUtil;
import com.carleasoft.mps.core.utils.IpUtils;
import com.carleasoft.mps.excel.utils.ConvertTemplatePath;
import com.carleasoft.mps.excel.utils.ExcelUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: yangHao
 * @createDate:2023/5/18
 * @description:
 */
@Service
public class EduDoorServiceImpl extends ServiceImpl<EduDoorMapper, EducationBasicEntity> implements EduDoorService {

    @Autowired
    private EduCollectService eduCollectService;
    @Autowired
    private EduOpenService eduOpenService;
    @Autowired
    private EducationService educationService;
    @Autowired
    private UserSkillService userSkillService;
    @Autowired
    private DealProcessService dealProcessService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CollectorService collectorService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveResource(EducationPo educationPo, HttpServletRequest request) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        String idStr = IdWorker.getIdStr();
        EducationBasicEntity educationBasicEntity = BeanUtil.copyProperties(educationPo, EducationBasicEntity.class);
        educationBasicEntity.setRName(educationPo.getName());
        educationBasicEntity.setRType(educationPo.getType());
        educationBasicEntity.setRCategory(educationPo.getCategory());
        educationBasicEntity.setREducation(educationPo.getEducation());
        educationBasicEntity.setCreateTime(LocalDateTime.now());
        educationBasicEntity.setCreatePersonCode(user.getUserCode());
        educationBasicEntity.setCreatePersonName(user.getUserName());
        educationBasicEntity.setUpdateTime(LocalDateTime.now());
        educationBasicEntity.setUpdatePersonCode(user.getUserCode());
        educationBasicEntity.setUpdatePersonName(user.getUserName());
        educationBasicEntity.setEduResourceCode(idStr);
        educationBasicEntity.setIsTop(0);
        String ipAddr = IpUtils.getIpAddr(request);
        EducationOpenEntity educationOpenEntity = new EducationOpenEntity();
        educationOpenEntity.setEduResourceCode(idStr);
        educationOpenEntity.setCreateTime(LocalDateTime.now());
        educationOpenEntity.setCreatePersonCode(user.getUserCode());
        educationOpenEntity.setCreatePersonName(user.getUserName());
        educationOpenEntity.setOpenType(3);
        educationOpenEntity.setIpAddress(ipAddr);
        eduOpenService.save(educationOpenEntity);
        return this.save(educationBasicEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateResource(EducationPo educationPo, HttpServletRequest request) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        EducationBasicEntity educationBasicEntity = this.getOne(Wrappers.<EducationBasicEntity>lambdaQuery()
                .eq(EducationBasicEntity::getEduResourceCode, educationPo.getEduResourceCode()));
        if (Objects.isNull(educationBasicEntity)) {
            throw new BusinessException(ExceptionCMSEnum.DATABASE_NO);
        }
        BeanUtil.copyProperties(educationPo, educationBasicEntity);
        educationBasicEntity.setRName(educationPo.getName());
        educationBasicEntity.setRType(educationPo.getType());
        educationBasicEntity.setRCategory(educationPo.getCategory());
        educationBasicEntity.setREducation(educationPo.getEducation());
        educationBasicEntity.setUpdatePersonCode(user.getUserCode());
        educationBasicEntity.setUpdatePersonName(user.getUserName());
        educationBasicEntity.setUpdateTime(LocalDateTime.now());
        eduOpenService.remove(Wrappers.<EducationOpenEntity>lambdaQuery().eq(EducationOpenEntity::getEduResourceCode, educationPo.getEduResourceCode())
                .eq(EducationOpenEntity::getOpenType, 3));
        // 获取ip地址
        String ipAddr = IpUtils.getIpAddr(request);
        EducationOpenEntity educationOpenEntity = new EducationOpenEntity();
        educationOpenEntity.setEduResourceCode(educationPo.getEduResourceCode());
        educationOpenEntity.setCreateTime(LocalDateTime.now());
        educationOpenEntity.setCreatePersonCode(user.getUserCode());
        educationOpenEntity.setCreatePersonName(user.getUserName());
        educationOpenEntity.setOpenType(3);
        educationOpenEntity.setIpAddress(ipAddr);
        eduOpenService.save(educationOpenEntity);
        return this.updateById(educationBasicEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean top(EducationPo educationPo) {
        return this.update(Wrappers.<EducationBasicEntity>lambdaUpdate()
                .eq(EducationBasicEntity::getEduResourceCode, educationPo.getEduResourceCode())
                .set(EducationBasicEntity::getIsTop, educationPo.getTopType()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(EducationPo educationPo) {
        eduOpenService.remove(Wrappers.<EducationOpenEntity>lambdaQuery()
                .eq(EducationOpenEntity::getEduResourceCode, educationPo.getEduResourceCode()));
        return this.remove(Wrappers.<EducationBasicEntity>lambdaQuery()
                .eq(EducationBasicEntity::getEduResourceCode, educationPo.getEduResourceCode()));
    }

    @Override
    public EducationCollectVo detail(EducationPo educationPo) {
        IBeanUtil.paramVerify(educationPo, "resource");
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        EducationBasicEntity educationBasicEntity = this.getOne(Wrappers.<EducationBasicEntity>lambdaQuery()
                .eq(EducationBasicEntity::getEduResourceCode, educationPo.getEduResourceCode()));
        if (Objects.isNull(educationBasicEntity)) {
            throw new BusinessException(ExceptionCMSEnum.NO_SOURCE_EXITS);
        }
        if (StrUtil.isNotBlank(educationBasicEntity.getContent()) && educationBasicEntity.getRType().equals(5) && educationPo.getIsDoor()) {
            String html = educationBasicEntity.getContent();
            Document doc = Jsoup.parse(html);
            Elements imgs = doc.select("img");
            if (imgs.size() > 0) {
                for (int i = 0; i < imgs.size(); i++) {
                    Element img = imgs.get(i);
                    String fileName = img.attr("alt");
                    String style = null;
                    String attr = img.attr("style");
                    if (StringUtils.isBlank(attr)) {
                        style = "width: 200px; height: 200px";
                    } else {
                        style = img.attr("style");
                    }
                    String result = "<ArmyImg fileName=\"" + fileName + "\" style=\"" + style + "\"></ArmyImg>";

                    if (html.contains(fileName)) {
                        html = html.replaceFirst("<img[^>]+>", result);
                    }
                }
                educationBasicEntity.setContent(html);
            }
        }
        if (Objects.nonNull(user) && user.getUserCode()!=null){
            if (!(user.getUserCode().equals(educationBasicEntity.getCreatePersonCode()) || user.getUserCat() == 3 || user.getUserCat() == 1)) {
                if (StrUtil.isNotBlank(educationBasicEntity.getPermission()) && educationPo.getResource() == 2) {
                    if (educationBasicEntity.getPermission().equals("[]")) {

                    } else {
                        String permission = educationBasicEntity.getPermission();
                        List<String> list = JSONObject.parseArray(permission, String.class);
                        int aaa = 0;
                        for (UserPro userPro : user.getUserPros()) {
                            for (UserDeptVo userDeptVo : userPro.getUserDeptVoList()) {
                                if (list.contains(userDeptVo.getDeptCode())) {
                                    aaa = 1;
                                    break;
                                }

                            }
                        }
                        if (aaa == 0) {
                            throw new BusinessException(ExceptionCMSEnum.NO_PERMISSION);
                        }
                    }

                }
            }
        }



        EducationCollectVo educationCollectVo = BeanUtil.copyProperties(educationBasicEntity, EducationCollectVo.class);
        educationCollectVo.setCategory(educationBasicEntity.getRCategory());
        if(StringUtils.isNotBlank(educationBasicEntity.getRCategory())){
            educationCollectVo.setCategoryName(eduCollectService.getOne(Wrappers.<EducationCollectEntity>lambdaQuery()
                    .eq(EducationCollectEntity::getCategoryCode, educationBasicEntity.getRCategory())).getCategoryName());
        }
        educationCollectVo.setName(educationBasicEntity.getRName());
        educationCollectVo.setEducation(educationBasicEntity.getREducation());
        EducationEntity educationServiceOne = educationService.getOne(Wrappers.<EducationEntity>lambdaQuery()
                .eq(EducationEntity::getEducationCode, educationBasicEntity.getREducation()));
        educationCollectVo.setEducationName(educationServiceOne.getEducationName());
        educationCollectVo.setType(educationBasicEntity.getRType());
        if (Objects.nonNull(user) && user.getUserCode() != null) {
            List<EducationOpenEntity> openEntities = eduOpenService.list(Wrappers.<EducationOpenEntity>lambdaQuery()
                    .eq(EducationOpenEntity::getEduResourceCode, educationPo.getEduResourceCode())
                    .eq(EducationOpenEntity::getCreatePersonCode, user.getUserCode())
                    .eq(EducationOpenEntity::getOpenType, 4));
            if (CollUtil.isNotEmpty(openEntities)) {
                educationCollectVo.setCollect(1);
            } else {
                educationCollectVo.setCollect(2);
            }
        }

        List<EducationOpenEntity> reasourceOpenEntities = eduOpenService.list(Wrappers.<EducationOpenEntity>lambdaQuery()
                .eq(EducationOpenEntity::getEduResourceCode, educationBasicEntity.getEduResourceCode()));
        Map<Integer, List<EducationOpenEntity>> map = reasourceOpenEntities.stream().collect(Collectors.groupingBy(EducationOpenEntity::getOpenType));
        if (map.containsKey(1)) {
            educationCollectVo.setDownloads(map.get(1).size());
        }
        if (map.containsKey(4)) {
            educationCollectVo.setCollector(map.get(4).size());
        }
        if (map.containsKey(2)) {
            educationCollectVo.setView(map.get(2).size());
        }
        //判断当前用户是否收藏了该资源信息
        if(StringUtils.isNotBlank(user.getUserCode())){
            EducationOpenEntity eduOpenServiceOne = eduOpenService.getOne(Wrappers.<EducationOpenEntity>lambdaQuery()
                    .eq(EducationOpenEntity::getEduResourceCode, educationBasicEntity.getEduResourceCode())
                    .eq(EducationOpenEntity::getCreatePersonCode,user.getUserCode())
                    .eq(EducationOpenEntity::getOpenType,4));
            if(Objects.isNull(eduOpenServiceOne)){
                educationCollectVo.setCollect(2);
            }else {
                educationCollectVo.setCollect(1);
            }
        }
        return educationCollectVo;
    }

    @Override
    public Page<EduPageQueryVo> doorPageQuery(Page page, EducationPageQueryPo educationPageQueryPo, HttpServletRequest request) {
        if (StrUtil.isNotBlank(educationPageQueryPo.getEducationCode())) {
            educationPageQueryPo.setEducation(educationPageQueryPo.getEducationCode());
        }
        Page<EduPageQueryVo> reasourcePageQueryVoPage = this.getBaseMapper().doorPageQuery(page, educationPageQueryPo);
        if (CollUtil.isNotEmpty(reasourcePageQueryVoPage.getRecords())) {
            List<String> reasourceCodes = reasourcePageQueryVoPage.getRecords().stream().map(EduPageQueryVo::getEduResourceCode).collect(Collectors.toList());
            List<EducationOpenEntity> reasourceOpenEntities = eduOpenService.list(Wrappers.<EducationOpenEntity>lambdaQuery()
                    .in(EducationOpenEntity::getEduResourceCode, reasourceCodes));
            Map<String, List<EducationOpenEntity>> listMap = reasourceOpenEntities.stream().collect(Collectors.groupingBy(EducationOpenEntity::getEduResourceCode));
            List<String> codes = reasourcePageQueryVoPage.getRecords().stream().map(EduPageQueryVo::getCategory).filter(Objects::nonNull).collect(Collectors.toList());
            List<EducationCollectEntity> reasourceCollectEntities = eduCollectService.list(Wrappers.<EducationCollectEntity>lambdaQuery()
                    .in(EducationCollectEntity::getCategoryCode, codes));
            Map<String, EducationCollectEntity> map = reasourceCollectEntities.stream().collect(Collectors.toMap(EducationCollectEntity::getCategoryCode, Function.identity()));
            Set<String> educationCodes = reasourcePageQueryVoPage.getRecords().stream().map(EduPageQueryVo::getEducation).collect(Collectors.toSet());
            List<EducationEntity> entities = educationService.list(Wrappers.<EducationEntity>lambdaQuery()
                    .in(EducationEntity::getEducationCode, educationCodes));
            Map<String, EducationEntity> entityMap = entities.stream().collect(Collectors.toMap(EducationEntity::getEducationCode, Function.identity()));
            for (EduPageQueryVo record : reasourcePageQueryVoPage.getRecords()) {
                if (entityMap.containsKey(record.getEducation())) {
                    record.setEducationName(entityMap.get(record.getEducation()).getEducationName());
                }
                if (map.containsKey(record.getCategory())) {
                    record.setCategoryName(map.get(record.getCategory()).getCategoryName());
                }
                if (listMap.containsKey(record.getEduResourceCode())) {
                    List<EducationOpenEntity> openEntities = listMap.get(record.getEduResourceCode());
                    Map<Integer, List<EducationOpenEntity>> integerListMap = openEntities.stream().collect(Collectors.groupingBy(EducationOpenEntity::getOpenType));
                    if (integerListMap.containsKey(2)) {
                        record.setView(integerListMap.get(2).size());
                    }
                    if (integerListMap.containsKey(4)) {
                        record.setCollector(integerListMap.get(4).size());
                    }
                }
            }
        }
        return reasourcePageQueryVoPage;
    }

    @Override
    public List<EducationEntity> getEducation() {
        List<EducationEntity> educationEntities = educationService.list(Wrappers.<EducationEntity>lambdaQuery()
                .eq(EducationEntity::getIsShow, 1));
        return educationEntities;
    }

    @Override
    public List<EducationCollectEntity> getCategory(EducationEntity reasourceEntity) {
        List<EducationCollectEntity> reasourceCollectEntities = eduCollectService.list(Wrappers.<EducationCollectEntity>lambdaQuery()
                .eq(EducationCollectEntity::getEducation, reasourceEntity.getEducationCode()));
        if (CollUtil.isNotEmpty(reasourceCollectEntities)) {
            List<String> categoryCodes = reasourceCollectEntities.stream().map(EducationCollectEntity::getCategoryCode).collect(Collectors.toList());
            List<EducationBasicEntity> reasourceEntities = this.list(Wrappers.<EducationBasicEntity>lambdaQuery()
                    .in(EducationBasicEntity::getRCategory, categoryCodes));
            Map<String, List<EducationBasicEntity>> map = reasourceEntities.stream().collect(Collectors.groupingBy(EducationBasicEntity::getRCategory));
            for (EducationCollectEntity educationCollectEntity : reasourceCollectEntities) {
                if (map.containsKey(educationCollectEntity.getCategoryCode())) {
                    educationCollectEntity.setSum(map.get(educationCollectEntity.getCategoryCode()).size());
                }
            }
        }

        return reasourceCollectEntities;
    }

    @Override
    public EduWorkCountVo workbenchCount() {
        EduWorkCountVo eduWorkCountVo = new EduWorkCountVo();
        int count = this.count();
        eduWorkCountVo.setResource(count);
        eduWorkCountVo.setTalents(userSkillService.count(Wrappers.<UserSkill>lambdaQuery()
                .eq(UserSkill::getIsDelete, 0)
                .eq(UserSkill::getUserType, 1)));
        int i = dealProcessService.count(Wrappers.<DealProcessEntity>lambdaQuery()
                .eq(DealProcessEntity::getState, 1)
                .eq(DealProcessEntity::getIsDelete, 0));
        eduWorkCountVo.setClerk(i);
        String categoryCode = "aedd68de17c14803b0a9d8111f5fcb0e";
        int aaa = articleService.count(categoryCode);
        eduWorkCountVo.setLaw(aaa);
        String code = "78ebbb38c93944baa47cc829695717c5";
        int bbb = articleService.count(code);
        eduWorkCountVo.setPsychology(bbb);
        return eduWorkCountVo;
    }

    @Override
    public List<EduCountVo> webCount() {
        List<EduCountVo> eduCountVos = new ArrayList<>();
        List<EducationEntity> educationEntities = educationService.list();
        if (CollUtil.isNotEmpty(educationEntities)) {
            Map<String, List<EducationBasicEntity>> map = new HashMap<>();
            List<String> educationCodes = educationEntities.stream().map(EducationEntity::getEducationCode).collect(Collectors.toList());
            List<EducationBasicEntity> reasourceEntities = this.list(Wrappers.<EducationBasicEntity>lambdaQuery()
                    .in(EducationBasicEntity::getREducation, educationCodes));
            if (CollUtil.isNotEmpty(reasourceEntities)) {
                map = reasourceEntities.stream().collect(Collectors.groupingBy(EducationBasicEntity::getREducation));
            }
            for (EducationEntity educationEntity : educationEntities) {
                if (educationEntity.getIsShow().equals(1)) {
                    EduCountVo eduCountVo = new EduCountVo();
                    eduCountVo.setName(educationEntity.getEducationName());
                    if (map.containsKey(educationEntity.getEducationCode())) {
                        eduCountVo.setSum(map.get(educationEntity.getEducationCode()).size());
                    }
                    eduCountVos.add(eduCountVo);
                }

            }
        }

        return eduCountVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(EducationCodePo educationCodePo, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        List<EducationBasicEntity> reasourceEntities = new ArrayList<>();
        List<EducationExcelVo> suppliesInformationVos = new ArrayList<>();
        if (StrUtil.isNotBlank(educationCodePo.getCode())) {
            reasourceEntities = this.list(Wrappers.<EducationBasicEntity>lambdaQuery()
                    .eq(EducationBasicEntity::getREducation, educationCodePo.getCode()));
        } else {
            reasourceEntities = this.list();
        }
        if (CollUtil.isNotEmpty(reasourceEntities)) {
            List<EducationEntity> educationEntities = educationService.list();
            Map<String, EducationEntity> entityMap = new HashMap<>();
            if (CollUtil.isNotEmpty(educationEntities)) {
                entityMap = educationEntities.stream().collect(Collectors.toMap(EducationEntity::getEducationCode, Function.identity()));
            }
            List<EducationCollectEntity> reasourceCollectEntities = eduCollectService.list();
            Map<String, EducationCollectEntity> collectEntityMap = new HashMap<>();
            if (CollUtil.isNotEmpty(reasourceCollectEntities)) {
                collectEntityMap = reasourceCollectEntities.stream().collect(Collectors.toMap(EducationCollectEntity::getCategoryCode, Function.identity()));
            }
            for (EducationBasicEntity educationBasicEntity : reasourceEntities) {
                EducationExcelVo educationExcelVo = new EducationExcelVo();
                educationExcelVo.setName(educationBasicEntity.getRName());
                if (entityMap.containsKey(educationBasicEntity.getREducation())) {
                    educationExcelVo.setEducation(entityMap.get(educationBasicEntity.getREducation()).getEducationName());
                }
                if (collectEntityMap.containsKey(educationBasicEntity.getRCategory())){
                    educationExcelVo.setCategory(collectEntityMap.get(educationBasicEntity.getRCategory()).getCategoryName());
                }
                educationExcelVo.setIntroduce(educationBasicEntity.getIntroduce());
                suppliesInformationVos.add(educationExcelVo);
            }
            map.put("list", suppliesInformationVos);
        }
        String path = "\\templates\\educationTmplace.xls";
        TemplateExportParams templatePath = new TemplateExportParams(ConvertTemplatePath.convertTemplatePath(path));
        try {
            String fileName="教育资源";
            ExcelUtils.exportExcel(templatePath, map, fileName, response);
//            ExcelUtils.exportExcel(templatePath, map, "", response);
        } catch (IOException e) {
            throw new BusinessException(ExceptionCMSEnum.NO_SOURCE_EXITS);
        }
        return true;
    }


    @Override
    public Page<EduPageQueryVo> pageQuery(Page page, EducationPageQueryPo educationPageQueryPo, HttpServletRequest request) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        educationPageQueryPo.setUserCode(user.getUserCode());
        Page<EduPageQueryVo> reasourcePageQueryVoPage = this.getBaseMapper().pageQuery(page, educationPageQueryPo);
        if (CollUtil.isNotEmpty(reasourcePageQueryVoPage.getRecords())) {
            List<String> codes = reasourcePageQueryVoPage.getRecords().stream().map(EduPageQueryVo::getCategory).filter(Objects::nonNull).collect(Collectors.toList());
            List<EducationCollectEntity> reasourceCollectEntities = eduCollectService.list(Wrappers.<EducationCollectEntity>lambdaQuery()
                    .in(EducationCollectEntity::getCategoryCode, codes));
            Map<String, EducationCollectEntity> map = reasourceCollectEntities.stream().collect(Collectors.toMap(EducationCollectEntity::getCategoryCode, Function.identity()));
            Set<String> educationCodes = reasourcePageQueryVoPage.getRecords().stream().map(EduPageQueryVo::getEducation).collect(Collectors.toSet());
            List<EducationEntity> entities = educationService.list(Wrappers.<EducationEntity>lambdaQuery()
                    .in(EducationEntity::getEducationCode, educationCodes));
            Map<String, EducationEntity> entityMap = entities.stream().collect(Collectors.toMap(EducationEntity::getEducationCode, Function.identity()));
            for (EduPageQueryVo record : reasourcePageQueryVoPage.getRecords()) {
                if (entityMap.containsKey(record.getEducation())) {
                    record.setEducationName(entityMap.get(record.getEducation()).getEducationName());
                }
                if (map.containsKey(record.getCategory())) {
                    record.setCategoryName(map.get(record.getCategory()).getCategoryName());
                }
            }
        }
        return reasourcePageQueryVoPage;
    }

    @Override
    public List<EduCategoryVo> getEducationByCategory(EducationPo educationPo) {
        List<EduCategoryVo> eduCategoryVos = new ArrayList<>();
        List<EducationCollectEntity> entities = eduCollectService.list(Wrappers.<EducationCollectEntity>lambdaQuery()
                .eq(EducationCollectEntity::getEducation, educationPo.getEducation()));
        if (CollUtil.isNotEmpty(entities)) {
            List<String> categoryCodes = entities.stream().map(EducationCollectEntity::getCategoryCode).collect(Collectors.toList());
            List<EducationBasicEntity> reasourceEntities = this.list(Wrappers.<EducationBasicEntity>lambdaQuery()
                    .in(EducationBasicEntity::getRCategory, categoryCodes));
            Map<String, List<EducationBasicEntity>> map = new HashMap<>();
            if (CollUtil.isNotEmpty(reasourceEntities)) {
                map = reasourceEntities.stream().collect(Collectors.groupingBy(EducationBasicEntity::getRCategory));
            }
            for (EducationCollectEntity entity : entities) {
                EduCategoryVo eduCategoryVo = new EduCategoryVo();
                eduCategoryVo.setCategoryCode(entity.getCategoryCode());
                eduCategoryVo.setCategoryName(entity.getCategoryName());
                if (map.containsKey(entity.getCategoryCode())) {
                    eduCategoryVo.setSum(map.get(entity.getCategoryCode()).size());
                } else {
                    eduCategoryVo.setSum(0);
                }
                eduCategoryVos.add(eduCategoryVo);
            }
        }
        return eduCategoryVos;
    }

    @Override
    public List<EduDoorListVo> doorList(EducationDoorPagePo educationDoorPagePo) {
        List<EduDoorListVo> eduDoorListVos = new ArrayList<>();
        List<EducationBasicEntity> reasourceEntities = new ArrayList<>();
        List<EducationEntity> educationEntities = educationService.list(Wrappers.<EducationEntity>lambdaQuery()
                .eq(EducationEntity::getIsShow, 1));
        if (CollUtil.isNotEmpty(educationEntities)) {
            List<String> code = educationEntities.stream().map(EducationEntity::getEducationCode).collect(Collectors.toList());
            LambdaQueryWrapper<EducationBasicEntity> wrapper = Wrappers.<EducationBasicEntity>lambdaQuery();
            if (educationDoorPagePo.getType() == 1) {
                wrapper.eq(EducationBasicEntity::getIsTop, 1);
                wrapper.in(EducationBasicEntity::getREducation, code);
                if (StrUtil.isNotBlank(educationDoorPagePo.getName())){
                    wrapper.like(EducationBasicEntity::getRName,educationDoorPagePo.getName());
                }
                wrapper.orderByDesc(EducationBasicEntity::getUpdateTime);
                reasourceEntities = this.list(wrapper);
            } else if (educationDoorPagePo.getType() == 2) {
                wrapper.in(EducationBasicEntity::getREducation, code);
                if (StrUtil.isNotBlank(educationDoorPagePo.getName())){
                    wrapper.like(EducationBasicEntity::getRName,educationDoorPagePo.getName());
                }
                wrapper.orderByDesc(EducationBasicEntity::getUpdateTime);
                reasourceEntities = this.list(wrapper);
            } else if (educationDoorPagePo.getType() == 3) {
                wrapper.eq(EducationBasicEntity::getRType, 4);
                wrapper.in(EducationBasicEntity::getREducation, code);
                if (StrUtil.isNotBlank(educationDoorPagePo.getName())){
                    wrapper.like(EducationBasicEntity::getRName,educationDoorPagePo.getName());
                }
                wrapper.orderByDesc(EducationBasicEntity::getUpdateTime);
                reasourceEntities = this.list(wrapper);
            } else if (educationDoorPagePo.getType() == 4 || educationDoorPagePo.getType() == 6) {
                wrapper.in(EducationBasicEntity::getREducation, code);
                if (StrUtil.isNotBlank(educationDoorPagePo.getName())){
                    wrapper.like(EducationBasicEntity::getRName,educationDoorPagePo.getName());
                }
                wrapper.orderByDesc(EducationBasicEntity::getUpdateTime);
                reasourceEntities = this.list(wrapper);
            } else if (educationDoorPagePo.getType() == 5) {
                //1代表为一个月    正的往前  负的为后
                Date date = stepMonth(new Date(), -1);
                wrapper.in(EducationBasicEntity::getREducation, code);
                wrapper.between(EducationBasicEntity::getUpdateTime, date, new Date());
                if (StrUtil.isNotBlank(educationDoorPagePo.getName())){
                    wrapper.like(EducationBasicEntity::getRName,educationDoorPagePo.getName());
                }
                wrapper.orderByDesc(EducationBasicEntity::getUpdateTime);
                reasourceEntities = this.list(wrapper);
            }
            if (CollUtil.isNotEmpty(reasourceEntities)) {
                List<String> resourceCodes = reasourceEntities.stream().map(EducationBasicEntity::getEduResourceCode).collect(Collectors.toList());
                List<EducationOpenEntity> reasourceOpenEntities = eduOpenService.list(Wrappers.<EducationOpenEntity>lambdaQuery()
                        .in(EducationOpenEntity::getEduResourceCode, resourceCodes));
                Map<String, List<EducationOpenEntity>> listMap = reasourceOpenEntities.stream().collect(Collectors.groupingBy(EducationOpenEntity::getEduResourceCode));
                Set<String> codes = reasourceEntities.stream().map(EducationBasicEntity::getRCategory).collect(Collectors.toSet());
                List<EducationCollectEntity> reasourceCollectEntities = eduCollectService.list(Wrappers.<EducationCollectEntity>lambdaQuery()
                        .in(EducationCollectEntity::getCategoryCode, codes));
                Map<String, EducationCollectEntity> map = reasourceCollectEntities.stream().collect(Collectors.toMap(EducationCollectEntity::getCategoryCode, Function.identity()));
                Set<String> educationCodes = reasourceEntities.stream().map(EducationBasicEntity::getREducation).collect(Collectors.toSet());
                List<EducationEntity> entities = educationService.list(Wrappers.<EducationEntity>lambdaQuery()
                        .in(EducationEntity::getEducationCode, educationCodes));
                Map<String, EducationEntity> entityMap = entities.stream().collect(Collectors.toMap(EducationEntity::getEducationCode, Function.identity()));
                for (EducationBasicEntity educationBasicEntity : reasourceEntities) {
                    EduDoorListVo eduDoorListVo = BeanUtil.copyProperties(educationBasicEntity, EduDoorListVo.class);
                    eduDoorListVo.setName(educationBasicEntity.getRName());
                    if (map.containsKey(educationBasicEntity.getRCategory())) {
                        eduDoorListVo.setCategoryName(map.get(educationBasicEntity.getRCategory()).getCategoryName());
                    }
                    if (entityMap.containsKey(educationBasicEntity.getREducation())) {
                        eduDoorListVo.setEducationName(entityMap.get(educationBasicEntity.getREducation()).getEducationName());

                    }
                    if (listMap.containsKey(educationBasicEntity.getEduResourceCode())) {
                        List<EducationOpenEntity> openEntities = listMap.get(educationBasicEntity.getEduResourceCode());
                        Map<Integer, List<EducationOpenEntity>> integerListMap = openEntities.stream().collect(Collectors.groupingBy(EducationOpenEntity::getOpenType));
                        if (integerListMap.containsKey(1)) {
                            eduDoorListVo.setDownloads(integerListMap.get(1).size());
                        }
                        if (integerListMap.containsKey(2)) {
                            eduDoorListVo.setView(integerListMap.get(2).size());
                        }
                        if (integerListMap.containsKey(4)) {
                            eduDoorListVo.setCollector(integerListMap.get(4).size());
                        }

                    }
                    eduDoorListVos.add(eduDoorListVo);
                }
                if (educationDoorPagePo.getType() == 4 || educationDoorPagePo.getType() == 5) {
                    if (CollUtil.isNotEmpty(eduDoorListVos)) {
                        return eduDoorListVos.stream().sorted(Comparator.comparing(EduDoorListVo::getView).reversed()).collect(Collectors.toList());
                    }
                }
                if (educationDoorPagePo.getType() == 6) {
                    return eduDoorListVos.stream().sorted(Comparator.comparing(EduDoorListVo::getCollector).reversed()).collect(Collectors.toList());
                }
            }
        }


        return eduDoorListVos;
    }

    @Override
    public List<EduDoorVo> doorEducation() {
        List<EduDoorVo> eduDoorVos = new ArrayList<>();
        List<EducationBasicEntity> reasourceEntities = this.list();
        Map<String, List<EducationBasicEntity>> map = reasourceEntities.stream().collect(Collectors.groupingBy(EducationBasicEntity::getREducation));
        List<EducationEntity> educationEntities = educationService.list(Wrappers.<EducationEntity>lambdaQuery()
                .eq(EducationEntity::getIsShow, 1));
        for (EducationEntity educationEntity : educationEntities) {
            EduDoorVo eduDoorVo = new EduDoorVo();
            eduDoorVo.setEducation(educationEntity.getEducationCode());
            eduDoorVo.setImage(educationEntity.getImage());
            eduDoorVo.setEducationName(educationEntity.getEducationName());
            if (map.containsKey(educationEntity.getEducationCode())) {
                List<EducationBasicEntity> entities = map.get(educationEntity.getEducationCode());
                List<EducationVo> educationVos = new ArrayList<>();
                entities.forEach(i -> {
                    educationVos.add(BeanUtil.copyProperties(i, EducationVo.class));
                });
                eduDoorVo.setResourceList(educationVos);
            }
            eduDoorVos.add(eduDoorVo);
        }
        return eduDoorVos;
    }

    @Override
    public List<EduVo> getEduInfo(EducationDoorPagePo educationDoorPagePo) {
        //查出所有显示的资源库
        List<EducationEntity> educationEntities = educationService.list(Wrappers.<EducationEntity>lambdaQuery()
                .eq(EducationEntity::getIsShow, 1));
        List<EduVo> eduVos = BeanUtil.copyToList(educationEntities,EduVo.class);
        for (EduVo vo : eduVos) {
            //获取分类
            List<EducationCollectEntity> educationCollectEntities = eduCollectService.list(Wrappers.<EducationCollectEntity>lambdaQuery()
                    .eq(EducationCollectEntity::getEducation, vo.getEducationCode()));
            if(educationCollectEntities.size() > 0 && CollUtil.isNotEmpty(educationCollectEntities)){
                List<EduCollectVo> eduCollectVos = BeanUtil.copyToList(educationCollectEntities,EduCollectVo.class);
                //获取分类里的数据
                for(EduCollectVo eduCollectVo:eduCollectVos){
//                    List<EducationBasicEntity> educationBasicEntities = this.list(Wrappers.<EducationBasicEntity>lambdaQuery()
//                            .eq(EducationBasicEntity::getRCategory, eduCollectVo.getCategoryCode()));
                    LambdaQueryWrapper<EducationBasicEntity> wrapper = Wrappers.<EducationBasicEntity>lambdaQuery();
                    wrapper.eq(EducationBasicEntity::getRCategory, eduCollectVo.getCategoryCode());
                    if (StrUtil.isNotBlank(educationDoorPagePo.getName())){
                        wrapper.like(EducationBasicEntity::getRName,educationDoorPagePo.getName());
                    }
                    wrapper.orderByDesc(EducationBasicEntity::getUpdateTime);
                    List<EducationBasicEntity> educationBasicEntities = this.list(wrapper);
                    List<EduBasicVo> eduBasicVos = BeanUtil.copyToList(educationBasicEntities, EduBasicVo.class);
                    eduCollectVo.setEduBasicVoList(eduBasicVos);
                    for(EduBasicVo eduBasicVo : eduBasicVos){
                        //获取数据量点击量
                        List<EducationOpenEntity> educationOpenEntities = eduOpenService.list(Wrappers.<EducationOpenEntity>lambdaQuery()
                                .eq(EducationOpenEntity::getEduResourceCode, eduBasicVo.getEduResourceCode()));
                        List<EduOpenVo> eduOpenVos = BeanUtil.copyToList(educationOpenEntities, EduOpenVo.class);
                        eduBasicVo.setEduOpenVoList(eduOpenVos);
                    }
                }
                vo.setEduCollectVoList(eduCollectVos);
            }
            //获取一级分类数据
            List<EducationBasicEntity> educationBasicEntities = this.list(Wrappers.<EducationBasicEntity>lambdaQuery()
                    .eq(EducationBasicEntity::getREducation, vo.getEducationCode()));
            List<EduBasicVo> basicVos = BeanUtil.copyToList(educationBasicEntities, EduBasicVo.class);
            vo.setEduBasicVoList(basicVos);
            //获取点击量
            for(EduBasicVo eduVo : basicVos){
                //获取数据量点击量
                List<EducationOpenEntity> educationOpenEntities = eduOpenService.list(Wrappers.<EducationOpenEntity>lambdaQuery()
                        .eq(EducationOpenEntity::getEduResourceCode, eduVo.getEduResourceCode()));
                List<EduOpenVo> eduOpenVos = BeanUtil.copyToList(educationOpenEntities, EduOpenVo.class);
                eduVo.setEduOpenVoList(eduOpenVos);
            }
        }
        return eduVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean viewDetail(EducationPo educationPo, HttpServletRequest request) {
        boolean isOk = false;
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        int aaa = 0;
        if (educationPo.getOpenType() != 5) {
            if (educationPo.getOpenType() == 4 || educationPo.getOpenType() == 1) {
                EducationOpenEntity reasourceOpenServiceOne = eduOpenService.getOne(Wrappers.<EducationOpenEntity>lambdaQuery()
                        .eq(EducationOpenEntity::getEduResourceCode, educationPo.getEduResourceCode())
                        .eq(EducationOpenEntity::getCreatePersonCode, user.getUserCode())
                        .eq(EducationOpenEntity::getOpenType, educationPo.getOpenType()));
                if (Objects.nonNull(reasourceOpenServiceOne)) {
                    aaa = 1;
                }
            }
            if (aaa == 0) {
                EducationOpenEntity educationOpenEntity = new EducationOpenEntity();
                educationOpenEntity.setEduResourceCode(educationPo.getEduResourceCode());
                educationOpenEntity.setIpAddress(IpUtils.getIpAddr(request));
                educationOpenEntity.setCreateTime(LocalDateTime.now());
                educationOpenEntity.setCreatePersonCode(user.getUserCode());
                educationOpenEntity.setCreatePersonName(user.getUserName());
                educationOpenEntity.setOpenType(educationPo.getOpenType());
                isOk = eduOpenService.save(educationOpenEntity);
            }

        } else {
            EducationOpenEntity reasourceOpenServiceOne = eduOpenService.getOne(Wrappers.<EducationOpenEntity>lambdaQuery()
                    .eq(EducationOpenEntity::getEduResourceCode, educationPo.getEduResourceCode())
                    .eq(EducationOpenEntity::getCreatePersonCode, user.getUserCode())
                    .eq(EducationOpenEntity::getOpenType, 4));
            isOk = eduOpenService.removeById(reasourceOpenServiceOne.getId());
        }
        EducationBasicEntity educationBasicEntity = this.getOne(Wrappers.<EducationBasicEntity>lambdaQuery()
                .eq(EducationBasicEntity::getEduResourceCode, educationPo.getEduResourceCode()));
        CollectorEntity collectorEntity = new CollectorEntity();
        collectorEntity.setUserCode(user.getUserCode());
        collectorEntity.setUserName(user.getUserName());
        collectorEntity.setName(educationBasicEntity.getRName());
        collectorEntity.setCode(educationPo.getEduResourceCode());
        collectorEntity.setImage(educationBasicEntity.getImage());
        collectorEntity.setType(1);
        if (educationPo.getOpenType() == 4) {
            isOk = collectorService.saveCollector(collectorEntity);
        }
        if (educationPo.getOpenType() == 5) {
            isOk = collectorService.delete(collectorEntity);
        }
        return isOk;
    }


    /**
     * * 在给定的日期加上或减去指定月份后的日期
     * *
     * * @param sourceDate 原始时间
     * * @param month      要调整的月份，向前为负数，向后为正数
     * * @return
     */
    public static Date stepMonth(Date sourceDate, int month) {
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH, month);
        return c.getTime();
    }

}
